/**************************************************************************************
 *
 * @(#) BaseBizImpl.java
 * @Package com.jgdt.jgdtkasannong_university_gene_backend.biz.content.impl
 **************************************************************************************/
package com.jgdt.jgdtkasannong_university_gene_backend.biz.content.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jgdt.jgdtkasannong_university_gene_backend.biz.content.BaseBiz;
import com.jgdt.jgdtkasannong_university_gene_backend.common.Sysconstant;
import com.jgdt.jgdtkasannong_university_gene_backend.common.response.PageRequest;
import com.jgdt.jgdtkasannong_university_gene_backend.config.enums.SysValueSetEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.dto.CameraDeviceSequenceDto;
import com.jgdt.jgdtkasannong_university_gene_backend.dto.EffectiveSequenceDto;
import com.jgdt.jgdtkasannong_university_gene_backend.dto.ReDeviceChannelsVo;
import com.jgdt.jgdtkasannong_university_gene_backend.dto.ReDeviceChannelsVoResult;
import com.jgdt.jgdtkasannong_university_gene_backend.entity.base.BaseInfo;
import com.jgdt.jgdtkasannong_university_gene_backend.entity.base.BaseRegion;
import com.jgdt.jgdtkasannong_university_gene_backend.entity.base.CameraDevice;
import com.jgdt.jgdtkasannong_university_gene_backend.entity.base.CameraDeviceChannel;
import com.jgdt.jgdtkasannong_university_gene_backend.entity.content.Media;
import com.jgdt.jgdtkasannong_university_gene_backend.enums.base.CloudVendorEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.enums.base.IsAccessVideoEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.enums.base.IsCloudEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.enums.content.BizTypeEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.enums.content.MediaTypeEnums;
import com.jgdt.jgdtkasannong_university_gene_backend.mapper.base.BaseInfoMapper;
import com.jgdt.jgdtkasannong_university_gene_backend.mapper.base.BaseRegionMapper;
import com.jgdt.jgdtkasannong_university_gene_backend.service.base.*;
import com.jgdt.jgdtkasannong_university_gene_backend.service.base.video.FireflyCloudEzvizService;
import com.jgdt.jgdtkasannong_university_gene_backend.service.content.MediaService;
import com.jgdt.jgdtkasannong_university_gene_backend.service.sys.SysValueSetService;
import com.jgdt.jgdtkasannong_university_gene_backend.utils.SecurityUtils;
import com.jgdt.jgdtkasannong_university_gene_backend.vo.base.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @description: 基地-biz实现
 * @author: huangAn
 * @createDate: 2025/04/24
 */
@Service
@Slf4j
public class BaseBizImpl implements BaseBiz {

    @Autowired
    private BaseRegionService baseRegionService;
    @Autowired
    private BaseInfoService baseInfoService;
    @Autowired
    private BaseRegionMapper baseRegionMapper;
    @Autowired
    private BaseInfoMapper baseInfoMapper;
    @Autowired
    private CameraDeviceService cameraDeviceService;
    @Autowired
    private MediaService mediaService;
    @Autowired
    private SysValueSetService sysValueSetService;
    @Autowired
    private FireflyCloudEzvizService fireflyCloudEzvizService;
    @Autowired
    private CameraDeviceSequenceService cameraDeviceSequenceService;
    @Autowired
    private CameraDeviceChannelService cameraDeviceChannelService;

    @Override
    public List<BaseRegionVo> queryBaseRegionByMenu(Integer menuId) {
        List<BaseRegionVo> regionVoList=new ArrayList<>();
        //校验
        if (menuId==null){
            return regionVoList;
        }
        //查询相关区域信息
        BaseRegion baseRegion=new BaseRegion();
        baseRegion.setMenuId(menuId);
        List<BaseRegion> baseRegionList=baseRegionService.getBaseRegionBy(baseRegion);
        if(CollectionUtil.isEmpty(baseRegionList)){
            return regionVoList;
        }
        //查询相关基地信息
        List<Integer> regionids=baseRegionList.stream().map(BaseRegion::getId).collect(Collectors.toList());
        List<BaseInfo> baseInfoList=baseInfoService.queryBaseInfoByRegionid(regionids);
        Map<Integer,List<BaseInfo>> baseInfoListMap= baseInfoList.stream().collect(Collectors.groupingBy(BaseInfo::getRegionid));

        for(BaseRegion region:baseRegionList){
            BaseRegionVo baseRegionVo=new BaseRegionVo();
            BeanUtils.copyProperties(region,baseRegionVo);
            //基地数据
            List<BaseInfo> baseInfos=baseInfoListMap.get(region.getId());
            if(CollectionUtil.isNotEmpty(baseInfos)){
                baseRegionVo.setBaseSum(baseInfos.size());
                List<RegionBaseInfoVo> regionBaseInfoVos= com.jgdt.jgdtkasannong_university_gene_backend.utils.BeanUtils.convertList(baseInfos,RegionBaseInfoVo.class);
                baseRegionVo.setBaseInfoVos(regionBaseInfoVos);
            }else {
                baseRegionVo.setBaseSum(0);
            }
            regionVoList.add(baseRegionVo);
        }
        return regionVoList;
    }

    @Override
    public RegionInfoVo queryRegionInfoById(Integer regionId) {
        RegionInfoVo regionInfoVo = new RegionInfoVo();
        if (regionId == null) {
            return regionInfoVo;
        }
        BaseRegion baseRegion = baseRegionMapper.selectById(regionId);
        if(ObjectUtils.isNotEmpty(baseRegion)){
            BeanUtils.copyProperties(baseRegion, regionInfoVo);
            //访问图片 frontImageUrl 赋值
            regionInfoVo.setFrontVarietyFemaleImg(mediaService.getImgUrl(regionInfoVo.getVarietyFemaleImg()));
            regionInfoVo.setFrontVarietyMaleImg(mediaService.getImgUrl(regionInfoVo.getVarietyMaleImg()));
        }
        return regionInfoVo;
    }

    @Override
    public BaseInfoVo queryBaseInfoById(PageRequest<QueryBaseInfoByIdParameter> requestPage) {
        BaseInfoVo baseInfoVo=new BaseInfoVo();
        if(ObjectUtils.isEmpty(requestPage.getCondition())){
            return baseInfoVo;
        }
        Integer baseId=requestPage.getCondition().getBaseId();
        if(baseId==null){
            return baseInfoVo;
        }
        BaseInfo baseInfo=baseInfoMapper.selectById(baseId);
        if(ObjectUtils.isEmpty(baseInfo)){
            return baseInfoVo;
        }
        //对应区域信息
        BaseRegion region=baseRegionMapper.selectById(baseInfo.getRegionid());
        if(ObjectUtils.isNotEmpty(region)){
            baseInfoVo.setRegionStrName(sysValueSetService.queryPriorityValueByCode(SysValueSetEnums.BASE_REGION_STRNAME.getCode())+region.getCity()+ Sysconstant.DIAGONAL+region.getDistrict());
        }

        //图片信息
        List<Media> mediaList=mediaService.queryByBaseId(Arrays.asList(baseInfo.getId()), MediaTypeEnums.IMG.getKey(), BizTypeEnums.BASE.getKey());
        if(CollectionUtil.isNotEmpty(mediaList)){
            baseInfoVo.setBaseImg(mediaList.get(0).getImageUrl());
            //frontImageUrl 赋值
            baseInfoVo.setFrontImageUrl(mediaService.getImgUrl(baseInfoVo.getBaseImg()));
        }
        BeanUtils.copyProperties(baseInfo,baseInfoVo);
        //视频相关信息
        //分页查询设备相关数据
        IPage<CameraDeviceSequenceDto> cameraDeviceSequenceDtoPage=cameraDeviceService.getCameraDeviceSequenceDtoPage(requestPage);
        if(ObjectUtils.isNotEmpty(cameraDeviceSequenceDtoPage)){
            //组装参数
            IPage<CameraDeviceVo> cameraDeviceVoPage=new Page<>(requestPage.getPageNum(),requestPage.getPageSize());
            cameraDeviceVoPage.setSize(cameraDeviceSequenceDtoPage.getSize());
            cameraDeviceVoPage.setTotal(cameraDeviceSequenceDtoPage.getTotal());
            cameraDeviceVoPage.setPages(cameraDeviceSequenceDtoPage.getPages());
            List<CameraDeviceVo> cameraDeviceVoList=new ArrayList<>();

            //查询所有相关设备序列号信息的通道信息
            List<CameraDeviceSequenceDto> pageRecords=cameraDeviceSequenceDtoPage.getRecords();
            if(CollectionUtil.isNotEmpty(pageRecords)){
                Map<String,CameraDeviceChannel> cameraDeviceChannelListMap=new HashMap<>();
                List<Integer> sequenceIds= pageRecords.stream().map(CameraDeviceSequenceDto::getSequenceId).distinct().collect(Collectors.toList());
                List<CameraDeviceChannel> cameraDeviceChannelList=cameraDeviceChannelService.getChannelBySequence(sequenceIds);
                if(CollectionUtil.isNotEmpty(cameraDeviceChannelList)){
                    cameraDeviceChannelListMap=cameraDeviceChannelList.stream().collect(Collectors.toMap(cameraDeviceChannel -> cameraDeviceChannel.getSequenceId()+"-"+cameraDeviceChannel.getChannelNo(),Function.identity()));
                }
                for(CameraDeviceSequenceDto deviceSequenceDto:pageRecords){
                    CameraDeviceVo cameraDeviceVo=new CameraDeviceVo();
                    BeanUtils.copyProperties(deviceSequenceDto,cameraDeviceVo);
                    //设置视频对象信息
                    cameraDeviceVo.setGetVidoVo(cameraDeviceSequenceService.getGetVidoVo(cameraDeviceChannelListMap,SecurityUtils.getCurrentUsername(),deviceSequenceDto.getSequenceId(),deviceSequenceDto.getChannelNo()));
                    cameraDeviceVoList.add(cameraDeviceVo);
                }
            }
            cameraDeviceVoPage.setRecords(cameraDeviceVoList);
            baseInfoVo.setPageCameraDeviceVo(cameraDeviceVoPage);
        }
        return baseInfoVo;
    }

    @Override
    public IPage<CameraDeviceVo> queryCameraDeviceVoPage(PageRequest<QueryBaseInfoByIdParameter> page) {
        IPage<CameraDeviceVo> cameraDeviceVoPage = new Page<>(page.getPageNum(), page.getPageSize());
        //分页查询设备相关数据
        IPage<CameraDeviceSequenceDto> cameraDeviceSequenceDtoPage = cameraDeviceService.getCameraDeviceSequenceDtoPage(page);
        if (ObjectUtils.isNotEmpty(cameraDeviceSequenceDtoPage)) {
            //组装参数
            cameraDeviceVoPage.setSize(cameraDeviceSequenceDtoPage.getSize());
            cameraDeviceVoPage.setTotal(cameraDeviceSequenceDtoPage.getTotal());
            cameraDeviceVoPage.setPages(cameraDeviceSequenceDtoPage.getPages());
            List<CameraDeviceVo> cameraDeviceVoList = new ArrayList<>();

            List<CameraDeviceSequenceDto> pageRecords=cameraDeviceSequenceDtoPage.getRecords();
            if(CollectionUtil.isNotEmpty(pageRecords)){
                Map<String,CameraDeviceChannel> cameraDeviceChannelListMap=new HashMap<>();
                List<Integer> sequenceIds= pageRecords.stream().map(CameraDeviceSequenceDto::getSequenceId).distinct().collect(Collectors.toList());
                List<CameraDeviceChannel> cameraDeviceChannelList=cameraDeviceChannelService.getChannelBySequence(sequenceIds);
                if(CollectionUtil.isNotEmpty(cameraDeviceChannelList)){
                    cameraDeviceChannelListMap=cameraDeviceChannelList.stream().collect(Collectors.toMap(cameraDeviceChannel -> cameraDeviceChannel.getSequenceId()+"-"+cameraDeviceChannel.getChannelNo(),Function.identity()));
                }
                for (CameraDeviceSequenceDto deviceSequenceDto : pageRecords) {
                    CameraDeviceVo cameraDeviceVo = new CameraDeviceVo();
                    BeanUtils.copyProperties(deviceSequenceDto, cameraDeviceVo);
                    //设置视频对象信息
                    cameraDeviceVo.setGetVidoVo(cameraDeviceSequenceService.getGetVidoVo(cameraDeviceChannelListMap,SecurityUtils.getCurrentUsername(),deviceSequenceDto.getSequenceId(),deviceSequenceDto.getChannelNo()));
                    cameraDeviceVoList.add(cameraDeviceVo);
                }
            }
            cameraDeviceVoPage.setRecords(cameraDeviceVoList);
        }
        return cameraDeviceVoPage;
    }

    @Override
    public void syncChannel() {
        log.info("执行syncChannel...");
        Date nowDate=new Date();
        //查询所有 符合要求的设备序列信息
        CameraDevice cameraDevice = new CameraDevice();
        cameraDevice.setIsAccessVideo(IsAccessVideoEnums.YES.getKey());
        cameraDevice.setIsCloud(IsCloudEnums.YES.getKey());
        cameraDevice.setCloudVendor(CloudVendorEnums.FLUORITE.getKey());
        List<EffectiveSequenceDto> effectiveSequenceDtoList = cameraDeviceSequenceService.getEffectiveSequence(cameraDevice);
        if (CollectionUtil.isEmpty(effectiveSequenceDtoList)) {
            log.warn("syncChannel effectiveSequenceDtoList 无数据,没有有效的设备与设备序列信息...");
            return;
        }
        //收集数据
        List<ReDeviceChannelsVoResult> reDeviceChannelsVoResultList = new ArrayList<>();
        for (EffectiveSequenceDto sequenceDto : effectiveSequenceDtoList) {
            //调用方法同步
            ReDeviceChannelsVoResult reDeviceChannelsVoResult = fireflyCloudEzvizService.getReDeviceChannels(sequenceDto.getSequenceId(), sequenceDto.getDvrSerialNumber(), sequenceDto.getCloudAuthAppkey(), sequenceDto.getCloudAuthAppsecret());
            if (ObjectUtils.isEmpty(reDeviceChannelsVoResult)) {
                log.warn("syncChannel warn:reDeviceChannelsVoResultList is null");
                continue;
            }
            reDeviceChannelsVoResultList.add(reDeviceChannelsVoResult);
        }
        if(CollectionUtil.isEmpty(reDeviceChannelsVoResultList)){
            log.warn("syncChannel warn:reDeviceChannelsVoResultList is null");
            return;
        }
        List<Integer> sequenceIds=new ArrayList<>();
        List<CameraDeviceChannel > cameraDeviceChannelList=new ArrayList<>();
        //组装数据 执行入库
        for(ReDeviceChannelsVoResult result:reDeviceChannelsVoResultList){
            if(!result.isGetErrBool()){
                sequenceIds.add(result.getSequenceId());
                List<ReDeviceChannelsVo> reDeviceChannelsVoList=result.getReDeviceChannelsVoList();
                for(ReDeviceChannelsVo reDeviceChannelsVo:reDeviceChannelsVoList){
                    CameraDeviceChannel cameraDeviceChannel=new CameraDeviceChannel();
                    BeanUtils.copyProperties(reDeviceChannelsVo,cameraDeviceChannel);
                    cameraDeviceChannel.setCreateTime(nowDate);
                    cameraDeviceChannel.setUpdateTime(nowDate);
                    cameraDeviceChannelList.add(cameraDeviceChannel);
                }
            }
        }
        if(CollectionUtil.isNotEmpty(sequenceIds)){
            //执行全量 同步数据
            cameraDeviceSequenceService.completeInsertIds(sequenceIds,cameraDeviceChannelList);
        }else{
            log.warn("syncChannel warn:sequenceIds为空...");
        }
    }
}




